package com.showsu.editor.utils.aliyun;


import com.alibaba.fastjson.JSON;
import com.aliyun.captcha20230305.models.VerifyCaptchaRequest;
import com.aliyun.captcha20230305.models.VerifyCaptchaResponse;
import com.aliyun.captcha20230305.Client;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * @Author: jph
 * @Description: 阿里云验证码工具类
 * @Date: Created in 13:00 下午 2023/8/15
 * @Modified By:
 */
@Slf4j
@Component
public class AliyunCaptchaUtil extends BaseAliyunUtil<Client> {

    @Value("${aliyun.yundunAFS.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.yundunAFS.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.yundunAFS.endpoint.captcha}")
    private String endpoint;

    @Override
    public void initClient(String accessKeyId, String accessKeySecret, String endpoint) {
        try {
            this.client= this.createClient(accessKeyId,accessKeySecret,endpoint);
        }catch (Exception e) {
            System.out.println("阿里云验证码工具类 实例化报错："+e.getMessage());
            throw new RuntimeException(e);
        }
    }
    @PostConstruct
    public void init(){
        System.out.println("开始实例化 阿里云验证码工具类");
        this.initClient(accessKeyId,accessKeySecret,endpoint);
        System.out.println("结束实例化 阿里云验证码工具类");
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @param endpoint
     * @return Client
     * @throws Exception
     */
    public Client createClient(String accessKeyId, String accessKeySecret,String endpoint) throws Exception {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Mts
        config.endpoint =endpoint;
        return new Client(config);
    }
    public Boolean run( Client client,VerifyCaptchaRequest request){
        // ====================== 3. 发起请求） ======================
        Boolean captchaVerifyResult =true;
        try {
            VerifyCaptchaResponse resp = client.verifyCaptcha(request);
            // 建议使用您系统中的日志组件，打印返回
            // 获取验证码验证结果（请注意判空），将结果返回给前端。出现异常建议认为验证通过，优先保证业务可用，然后尽快排查异常原因。
            if(resp!=null&&resp.body!=null&&resp.body.result!=null){
                captchaVerifyResult = resp.body.result.verifyResult;
            }
            try {
                if(!"200".equals(resp.getStatusCode().toString())
                        ||!resp.getBody().getSuccess()
                        ||!"Success".equalsIgnoreCase(resp.getBody().getCode())){
                    log.error("阿里云验证码工具类 verifyCaptcha 参数:{}, 报错:{}",request.getCaptchaVerifyParam(), JSON.toJSONString(resp));
                }
            }catch (Exception e){
                log.error("阿里云验证码工具类 verifyCaptcha 参数:{}, 报错:{}",request.getCaptchaVerifyParam(), e.getMessage());
            }
        } catch (TeaException error) {
            // 建议使用您系统中的日志组件，打印异常
            // 出现异常建议认为验证通过，优先保证业务可用，然后尽快排查异常原因。
            captchaVerifyResult = true;
            log.error("阿里云验证码工具类 verifyCaptcha 参数:{}, 报错:{}",request.getCaptchaVerifyParam(),error.getMessage());
        } catch (Exception _error) {
//            TeaException error = new TeaException(_error.getMessage(), _error);
            // 建议使用您系统中的日志组件，打印异常
            // 出现异常建议认为验证通过，优先保证业务可用，然后尽快排查异常原因。
            captchaVerifyResult = true;
            log.error("阿里云验证码工具类 verifyCaptcha 参数:{}, 报错:{}",request.getCaptchaVerifyParam(),_error.getMessage());
        }
        return captchaVerifyResult;
    }

    public Boolean start(Client thisClient,String captchaVerifyParam) {
        VerifyCaptchaRequest request = new VerifyCaptchaRequest();
        // 前端传来的验证参数 CaptchaVerifyParam
        request.setCaptchaVerifyParam(captchaVerifyParam);
        return run(thisClient,request);
    }

    public Boolean start(String accessKeyId,String accessKeySecret,String endpoint,String captchaVerifyParam) {
        try {
            Client newClient= this.createClient(accessKeyId,accessKeySecret,endpoint);
            return start(newClient,captchaVerifyParam);
        }catch (Exception e) {
            log.error("start方法 阿里云验证码工具类 实例化报错："+e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public Boolean start(String captchaVerifyParam) {
        if(this.client==null){
            return start(accessKeyId, accessKeySecret, endpoint, captchaVerifyParam);
        }
        return start(this.client,captchaVerifyParam);
    }



}
